package com.me.ss;
//author Ma7moud AbdulFatah
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Sol extends ListActivity {
	private LayoutInflater mInflater;
	RowData rd;
	DBConnectivity db = new DBConnectivity();
	int pagenum = 1;
	Object c = db.solutions(pagenum);
	ViewHolder holder = null;
	RowData rowData;
	Bitmap bitmap[];
	Handler handler = new Handler();
	Button add_news;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		if (!InternetChecking.checkInternetConnection(getApplicationContext())) {
			Toast.makeText(getApplicationContext(), "No Internet Connection",
					Toast.LENGTH_SHORT).show();
			return;
		} else {
			final ProgressDialog dialog = ProgressDialog.show(Sol.this, "",
					"Loading. Please wait...", true);
			super.onCreate(savedInstanceState);
			setContentView(R.layout.solutions);
			mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
			// 3abeeh be 5 items bas men el db
			// add_news = (Button) findViewById(R.id.add);
			System.out.println(VirtualStore.isLogin);
			/*
			 * if (VirtualStore.isLogin) add_news.setVisibility(View.VISIBLE);
			 * else add_news.setVisibility(View.INVISIBLE);
			 */
			// final Vector<RowData> data = new Vector<RowData>();
			final Button next = (Button) findViewById(R.id.s_next);
			final Button previous = (Button) findViewById(R.id.s_prev);
			Button contact = (Button) findViewById(R.id.s_cont);
			contact.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// Context mContext = getApplicationContext();
					Dialog dialoge = new Dialog(Sol.this);
					dialoge.setContentView(R.layout.contzct);
					dialoge.setTitle(" Please contact us");
					dialoge.show();
					db.home();
					TextView tel = (TextView) dialoge.findViewById(R.id.d_tel);
					tel.setText("Tel: " + db.Tel);
					TextView fax = (TextView) dialoge.findViewById(R.id.d_fax);
					fax.setText("Fax: " + db.Fax);
					ImageView image = (ImageView) dialoge
							.findViewById(R.id.image);
					image.setImageResource(R.drawable.contactus);
				}
			});
			previous.setVisibility(20);
			next.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// reloadListWithData(null);
					if (VirtualStore.sol_art_tit.isEmpty())
						return;
					else {
						final ProgressDialog dialog1 = ProgressDialog.show(
								Sol.this, "",
								"Retrieving Data. Please wait...", true);
						previous.setVisibility(0);
						pagenum++;
						db.solutions(pagenum);
						if (VirtualStore.sol_art_tit.isEmpty()) {
							next.setVisibility(10);
							Toast.makeText(getApplicationContext(),
									"No more Pages", Toast.LENGTH_SHORT).show();
							return;
						}
						// System.out.println(VirtualStore.photo.get(0));
						new Thread() {
							public void run() {
								super.run();
								final Vector<RowData> data = new Vector<RowData>();
								//
								loadImage(data);
								handler.post(new Runnable() {

									@Override
									public void run() {
										// TODO Auto-generated method stub
										reloadListWithData(data);
										System.out.println(data);
										getListView()
												.setTextFilterEnabled(true);
										dialog1.cancel();
									}
								});
							};
						}.start();

					}
				}
			});

			previous.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// reloadListWithData(null);
					final ProgressDialog dialog1 = ProgressDialog.show(
							Sol.this, "", "Loading. Please wait...", true);
					previous.setVisibility(0);
					pagenum--;
					db.solutions(pagenum);
					if (VirtualStore.sol_art_tit.isEmpty()) {
						previous.setVisibility(10);
						Toast.makeText(getApplicationContext(),
								"No more Pages", Toast.LENGTH_SHORT).show();
					}
					// System.out.println(VirtualStore.photo.get(0));
					new Thread() {
						public void run() {
							super.run();

							final Vector<RowData> data = new Vector<RowData>();
							loadImage(data);
							handler.post(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									reloadListWithData(data);
									getListView().setTextFilterEnabled(true);
									dialog1.cancel();
								}
							});
						};
					}.start();

				}
			});

			new Thread() {
				public void run() {
					super.run();
					final Vector<RowData> data = new Vector<RowData>();
					loadImage(data);
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							reloadListWithData(data);
							getListView().setTextFilterEnabled(true);
							dialog.cancel();
						}
					});
				};
			}.start();
		}
		final Dialog dialoge = new Dialog(Sol.this);
		final SharedPreferences myData = getSharedPreferences("My Data",
				MODE_PRIVATE);
		final SharedPreferences.Editor prefEditor = myData.edit();
		Button login = (Button) findViewById(R.id.s_login);
		if (VirtualStore.isLogin) {
			login.setText("Account");
			login.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent showContent = new Intent(getApplicationContext(),
							ay5ra.class);
					startActivity(showContent);

				}
			});

		} else {
			login.setText("Login");
			login.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					dialoge.setContentView(R.layout.login);
					dialoge.setTitle("Login Form");
					dialoge.setCancelable(true);
					dialoge.show();
					final CheckBox check = (CheckBox) dialoge
							.findViewById(R.id.check);
					check.setChecked(true);
					Button on = (Button) dialoge.findViewById(R.id.d_log);
					on.setOnClickListener(new View.OnClickListener() {
						EditText tx1 = (EditText) dialoge
								.findViewById(R.id.d_eun);
						EditText tx2 = (EditText) dialoge
								.findViewById(R.id.d_epass);

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Login lo = new Login();
							String Name = tx1.getText().toString();
							String Pass = tx2.getText().toString();
							try {
								if (Name.length() == 0 && Pass.length() == 0) {
									Toast.makeText(
											getApplicationContext(),
											"Enter User Name & Password, Please!",
											Toast.LENGTH_SHORT).show();
								} else if (Name.length() == 0) {
									Toast.makeText(getApplicationContext(),
											"Enter User Name, Please!",
											Toast.LENGTH_SHORT).show();
								} else if (Pass.length() == 0) {
									Toast.makeText(getApplicationContext(),
											"Enter Password, Please!",
											Toast.LENGTH_SHORT).show();
								} else {
									String hashedPass = lo.md5hash(Pass);
									lo.doLogin(Name, hashedPass);
								}

							} catch (NoSuchAlgorithmException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							VirtualStore.checked = check.isChecked();
							if (VirtualStore.ba && VirtualStore.checked) {
								Button log = (Button) findViewById(R.id.s_login);
								log.setText("Account");
								VirtualStore.isLogin = true;
								// add_news.setVisibility(View.VISIBLE);
								prefEditor.putString("UserName", tx1.getText()
										.toString());
								prefEditor.putString("Pass", tx2.getText()
										.toString());
								prefEditor.commit();
								Toast toast = Toast.makeText(
										getApplicationContext(),
										"Login Success", Toast.LENGTH_SHORT);
								toast.show();
								dialoge.cancel();
							}

							else if (VirtualStore.ba && !VirtualStore.checked) {
								Button log = (Button) findViewById(R.id.s_login);
								log.setText("Account");
								VirtualStore.isLogin = true;
								dialoge.cancel();
								Toast toast = Toast.makeText(
										getApplicationContext(),
										"Login Success", Toast.LENGTH_SHORT);
								toast.show();

							} else if (!VirtualStore.ba && tx1.length() != 0
									&& tx2.length() != 0) {
								Toast toast = Toast.makeText(
										getApplicationContext(),
										"Wrong Name or Password",
										Toast.LENGTH_SHORT);
								toast.show();
							}
							// dialog.cancel();
							Button login1 = (Button) findViewById(R.id.s_login);
							login1.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									Intent showContent = new Intent(
											getApplicationContext(),
											ay5ra.class);
									startActivity(showContent);

								}
							});

						}

					});

				}
			});
		}
		Button reg = (Button) findViewById(R.id.s_reg);
		reg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg2) {
				// TODO Auto-generated method stub
				Intent showContent = new Intent(getApplicationContext(),
						Register.class);
				startActivity(showContent);
			}
		});

		/*
		 * add_news.setOnClickListener(new View.OnClickListener() {
		 * 
		 * @Override public void onClick(View arg0) { // TODO Auto-generated
		 * method stub Intent showContent = new Intent(getApplicationContext(),
		 * AddNews.class); startActivity(showContent); } });
		 */
	}

	// CustomAdapter adapter = new CustomAdapter(this, R.layout.list1,
	// R.id.l_title, data);

	private void loadImage(final Vector<RowData> data) {
		int ha = VirtualStore.sol_art_tit.size();
		for (int i = 0; i < ha; i++) {
			try {
				String a = VirtualStore.sol_photo.get(i);
				// System.out.println(a);
				Bitmap btm;
				btm = BitmapFactory.decodeStream((InputStream) new URL(a)
						.getContent());
				rd = new RowData(i, VirtualStore.sol_art_tit.get(i),
						VirtualStore.sol_art_det.get(i), btm);
				data.add(rd);

			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();

			}
		}
	}

	private void reloadListWithData(final Vector<RowData> data) {
		BaseAdapter adapter = new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {

				rowData = (RowData) getItem(position);
				if (null == convertView) {
					convertView = mInflater.inflate(R.layout.list2, null);
					holder = new ViewHolder(convertView);
					convertView.setTag(holder);
				}
				holder = (ViewHolder) convertView.getTag();
				ImageView i = holder.getImage();
				i.setImageResource(R.drawable.unload);
				i.setImageBitmap(rowData.mImage);
				TextView title1 = holder.gettitle();
				title1.setText(rowData.mTitle);
				TextView detail1 = holder.getdetail();
				detail1.setText(rowData.mDetail);
				return convertView;
			}

			@Override
			public long getItemId(int arg0) {

				return data.get(arg0).mId;
			}

			@Override
			public Object getItem(int arg0) {

				return data.get(arg0);

			}

			@Override
			public int getCount() {
				return data.size();
			}
		};
		setListAdapter(adapter);

	}

	public void onListItemClick(ListView parent, View v, int position, long id) {
		int po;
		po = position + (pagenum - 1) * 5 + 1;
		VirtualStore.p_sol_id = po;
		System.out.println(pagenum);
		db.solutions(pagenum);
		Intent showContent = new Intent(getApplicationContext(), SolView.class);
		startActivity(showContent);
	}

	private class RowData {
		protected int mId;
		protected String mTitle;
		protected String mDetail;

		protected Bitmap mImage;

		RowData(int id, String title, String detail, Bitmap Image) {
			mId = id;
			mTitle = title;
			mDetail = detail;
			mImage = Image;
		}

		@Override
		public String toString() {
			return mId + " " + mTitle + " " + mDetail;
		}
	}

	private class ViewHolder {
		private View mRow;
		private TextView title = null;
		private TextView detail = null;
		private ImageView dd = null;

		public ViewHolder(View row) {
			mRow = row;
		}

		public ImageView getImage() {
			if (null == dd) {
				dd = (ImageView) mRow.findViewById(R.id.s_img);

			}
			return dd;
		}

		public TextView gettitle() {
			if (null == title) {
				title = (TextView) mRow.findViewById(R.id.sl_title);

			}
			return title;
		}

		public TextView getdetail() {
			if (null == detail) {
				detail = (TextView) mRow.findViewById(R.id.sl_detail);
			}
			return detail;
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (VirtualStore.ba && VirtualStore.checked) {
			Button log = (Button) findViewById(R.id.s_login);
			log.setText("MyAccount");
			log.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent showContent = new Intent(getApplicationContext(),
							ay5ra.class);
					startActivity(showContent);
				}
			});
		}

	}

}
